package dbadapters;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import entities.Student;

/**
 * use to change a students info in the db when a change is made in the system
 * 
 * @author gke703
 */
public class ChangeStudentdb {

	/**
	 * Replaces db entries for student with id of myStudent with new info for
	 * myStudent if myStudent is not in db it will be added
	 * 
	 * @param myStudent
	 *            student to be replaced/updated
	 */
	public ChangeStudentdb(Student myStudent) {

		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException cnfe) {
			System.out.println("Couldn't find driver class:");
			cnfe.printStackTrace();
		}

		Connection c = null;
		try {
			c = DriverManager.getConnection(
					"jdbc:postgresql://papyrus.usask.ca/cmpt370group00",
					"cmpt370group00", "an7x482d");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println(e);
		}

		Statement stmt = null;
		try {
			stmt = c.createStatement();
		} catch (SQLException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}

		try {
			// remove the existing copies of the student from the db
			stmt.execute("DELETE FROM students WHERE student_id="
					+ myStudent.getID());
			stmt.execute("DELETE FROM students_financialinfo WHERE student_id="
					+ myStudent.getID());
			stmt.execute("DELETE FROM students_loans WHERE student_id="
					+ myStudent.getID());
			stmt.execute("DELETE FROM cosigners WHERE student_id="
					+ myStudent.getID());
			if (myStudent.getPaymentPlanCreated()) {
				stmt.execute("DELETE FROM payment_plan WHERE student_id="
						+ myStudent.getID());
			}
		} catch (SQLException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}

		// Cleanup
		try {
			stmt.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// now re-add the student with the updated info
		new AddStudentDB(myStudent);

	}

}
